<template>
    <div v-if="!composeRuleComponentShow">
        <a-row>
            <a-space>
                创建者(负责人)
                <a-select
                    :options="userOptions"
                    show-search
                    :filter-option="filterOption"
                    style="width: 100px"
                    v-model:value="searchParams.create_id"
                ></a-select>
                网站组
                <a-select
                    :options="websiteGroupOptions"
                    v-model:value="searchParams.website_group_id"
                    show-search
                    :filter-option="filterOption"
                    style="width: 140px"
                ></a-select>
                行业类型
                <a-select
                    :options="websiteTypeOptions"
                    v-model:value="searchParams.trade_type_id"
                    show-search
                    :filter-option="filterOption"
                    style="width: 90px"
                ></a-select>
                <a-input placeholder="输入索引或规则名或备注..." v-model:value="search" style="width: 200px"></a-input>
                <a-button type="primary" @click="searchFunc" :loading="searchLoading">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    搜索
                </a-button>
                <a-button type="dashed">
                    <template #icon>
                        <download-outlined />
                    </template>
                    导出搜索结果
                </a-button>
            </a-space>
        </a-row>
        <br />
        <a-spin :spinning="tableLoading" :style="spinStyle">
            <a-table
                sticky
                :columns="columns"
                :data-source="tableData"
                @change="handleTableChange"
                :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                bordered
                :rowKey="createRowKey"
                :pagination="false"
                size="small"
            >
            </a-table>
            <br />
            <a-row justify="center" v-if="total > 10">
                <a-pagination
                    v-model:current="page"
                    showSizeChanger
                    v-model:pageSize="size"
                    show-quick-jumper
                    :total="total"
                    @change="pageChange"
                    :show-total="(total: number) => `总计 ${total} 项`"
                />
            </a-row>
        </a-spin>
    </div>
    <div v-if="currentUpdateComposeRule !== null && composeRuleComponentShow">
        <ComposeRule v-model:rule="currentUpdateComposeRule" @save:rule="updateComposeRuleCallback" save-rule-btn-text="保存规则">
            <template #back>
                <a-button type="dashed" danger @click="backUpdateView">退出</a-button>
            </template>
        </ComposeRule>
    </div>
    <GenerateArticleErrorContent v-model:visible="showErrorGenerateArticle" :errorDataList="errorDataList" />
</template>

<script lang="ts" setup>
    import { message, type TableProps } from "ant-design-vue";
    import { useCreateTableColumns, useHandleTableData, type TableData } from "@/hooks/useComposeRule";
    import { useCommonAsyncOptions, useCommonStaticOptions } from "@/hooks/useEsArticleCommon";
    import { SearchOutlined, DownloadOutlined } from "@ant-design/icons-vue";
    import { composeRuleApi } from "@/api/esArticle";
    import { cloneDeep } from "@/utils/lodash";
    import ComposeRule from "@/components/ComposeRule.vue";
    import GenerateArticleErrorContent from "@/tsx/composeRule/GenerateArticleErrorContent";
    import { useSpinLoadingState } from "@/hooks/useCommon";
    const { spinStyle, viewLoading: tableLoading } = useSpinLoadingState();
    const { userOptions, websiteGroupOptions, websiteTypeOptions } = useCommonAsyncOptions("get");
    const { filterOption } = useCommonStaticOptions();
    const {
        columns,
        isReloadRuleList,
        currentUpdateComposeRule,
        composeRuleComponentShow,
        errorDataList,
        showErrorGenerateArticle
    } = useCreateTableColumns();
    const tableData = ref<TableData>();

    // 当前页变化
    const pageChange = (pageNumber: number) => {
        page.value = pageNumber;
        getComposeRuleList();
    };
    // 总数
    const total = ref(0);

    const searchParams: GetComposeRuleParmas = reactive({
        create_id: 0,
        search: "",
        size: 10,
        page: 1,
        website_group_id: 0,
        trade_type_id: 0,
        order: "",
        sort_field: ""
    });
    // 分页
    const { size, page, search } = toRefs(searchParams);
    // 分页或者排序时触发
    const handleTableChange: TableProps["onChange"] = (pag, filters: any, sorter: any) => {
        if (sorter.order) {
            searchParams.order = sorter.order.slice(0, sorter.order.length - 3);
            searchParams.sort_field = sorter.field;
        } else {
            searchParams.order = "";
        }
        getComposeRuleList();
    };
    // 创建行key
    const createRowKey = (item: any) => item.id;
    // 表格选中的行key
    const selectedRowKeys = ref<Array<string>>([]);
    const onSelectChange = (keys: any) => {
        selectedRowKeys.value = keys;
    };
    // 获取规则列表
    const getComposeRuleList = () => {
        const params = cloneDeep(searchParams);
        for (const key in params) {
            if (!Reflect.get(params, key)) {
                Reflect.deleteProperty(params, key);
            }
        }
        tableLoading.value = true;
        return composeRuleApi(params, "get")
            .then((res) => {
                if (res.data.code === 200) {
                    const data = res.data.data;
                    total.value = res.data.count;
                    tableData.value = useHandleTableData(data, userOptions, websiteGroupOptions, websiteTypeOptions);
                } else {
                    message.error("获取失败!");
                }
            })
            .catch(() => {
                message.error("服务器错误!");
            })
            .finally(() => {
                tableLoading.value = false;
                isReloadRuleList.value = false;
            });
    };
    // 搜索按钮加载
    const searchLoading = ref(false);
    // 搜索
    const searchFunc = async () => {
        searchLoading.value = true;
        await getComposeRuleList();
        searchLoading.value = false;
    };
    // 导出搜索结果
    const exportSearch = () => {
        // 导出
    };
    // 退出修改页面
    const backUpdateView = () => {
        composeRuleComponentShow.value = false;
        currentUpdateComposeRule.value = null;
    };
    onMounted(() => {
        getComposeRuleList();
    });
    // 是否重新加载
    watch(isReloadRuleList, (newVal) => {
        newVal && getComposeRuleList();
    });
    // 修改组合规则
    const updateComposeRuleCallback = () => {
        if (currentUpdateComposeRule.value) {
            // @ts-ignore
            const id = currentUpdateComposeRule.value["id"];
            const params: PostComposeRuleParmas = cloneDeep(currentUpdateComposeRule.value);
            // @ts-ignore
            Reflect.deleteProperty(params, "id");
            return composeRuleApi({ id, data: params }, "put")
                .then((res) => {
                    if (res.data.code === 200) {
                        message.success("修改成功!");
                        isReloadRuleList.value = true;
                    } else {
                        message.error("修改失败!");
                    }
                })
                .catch(() => {
                    message.error("服务器错误!");
                });
        }
    };
</script>

<style scoped lang="scss"></style>
